package com.cskaoyan.service;

import com.cskaoyan.bean.bo.BaseParam;
import com.cskaoyan.bean.bo.RegisterBO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.user.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.ConstantProperties;
import com.cskaoyan.util.Md5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yemingfei
 * @since 2022/06/05 15:10
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    FootprintMapper footprintMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    FeedbackMapper feedbackMapper;

    @Autowired
    ConstantProperties CONSTANT;

    @Autowired
    CodeService codeService;

    /**
     * 用户注册接口
     */
    @Override
    public BaseRespVo register(RegisterBO registerBO) {

        // 获取code列表
        String[] codes = codeService.getCode(registerBO.getMobile());
        for (String code : codes) {
            if (registerBO.getCode().equals(code)) {
                // 密码加密
                String md5 = Md5Util.getMD5(registerBO.getPassword());
                // 用户信息封装
                User user = new User();
                user.setUsername(registerBO.getUsername());
                user.setPassword(md5);
                user.setMobile(registerBO.getMobile());
                user.setSessionKey(registerBO.getWxCode());
                user.setAddTime(new Date(System.currentTimeMillis()));
                user.setUpdateTime(new Date(System.currentTimeMillis()));
                user.setDeleted(false);
                // 新增用户
                userMapper.insertSelective(user);
                return BaseRespVo.ok(user);
            }
        }
        return BaseRespVo.invalidData();
    }

    /**
     * 显示会员信息列表
     *
     * @param param
     * @param username 查找时输入的用户名
     * @param userId   查找时输入的用户Id
     * @param mobile   查找时输入的手机号
     * @return
     */
    @Override
    public MemberData memberList(BaseParam param, String username, Integer userId, String mobile) {
        // 开始分页，从第几页，每页有多少数据
        PageHelper.startPage(param.getPage(), param.getLimit());
        // 返回数据
        // 查询
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        // 排序
        userExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 条件查询
        if (username != null) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (userId != null) {
            criteria.andIdEqualTo(userId);
        }
        if (mobile != null) {
            criteria.andMobileLike("%" + mobile + "%");
        }
        // 未逻辑删除的信息
        criteria.andDeletedEqualTo(false);
        List<User> users = userMapper.selectByExample(userExample);
        // 返回的VO没有birthday字段
        List<MemberDataListBean> list = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            MemberDataListBean memberDataListBean = new MemberDataListBean(
                    users.get(i).getId(),
                    users.get(i).getUsername(),
                    users.get(i).getPassword(),
                    users.get(i).getGender(),
                    users.get(i).getLastLoginTime(),
                    users.get(i).getLastLoginIp(),
                    users.get(i).getUserLevel(),
                    users.get(i).getNickname(),
                    users.get(i).getMobile(),
                    users.get(i).getAvatar(),
                    users.get(i).getWeixinOpenid(),
                    users.get(i).getSessionKey(),
                    users.get(i).getStatus(),
                    users.get(i).getAddTime(),
                    users.get(i).getUpdateTime(),
                    users.get(i).getDeleted());
            list.add(memberDataListBean);
        }
        // 设置分页
        PageInfo pageInfo = new PageInfo(list);
        // 共有几条数据
        long total = pageInfo.getTotal();
        // 共有几页
        int pages = pageInfo.getPages();
        return new MemberData(((int) total), pages, param.getLimit(), param.getPage(), list);
    }

    @Override
    public int memberIdIsExist(Integer id) {
        int count = userMapper.queryUserByIdAndDelete(id, false);
        if (count == 0) {
            return CONSTANT.getFailCode1();
        }
        return 0;
    }

    @Override
    public MemberDataListBean memberDetail(Integer id) {
        MemberDataListBean memberDataListBean = userMapper.queryUserById(id);
        return memberDataListBean;
    }

    @Override
    public void update(MemberDataListBean memberDataListBean) {
        Date birthday = null;
        User user = new User(
                memberDataListBean.getId(),
                memberDataListBean.getUsername(),
                memberDataListBean.getPassword(),
                memberDataListBean.getGender(),
                birthday,
                memberDataListBean.getLastLoginTime(),
                memberDataListBean.getLastLoginIp(),
                memberDataListBean.getUserLevel(),
                memberDataListBean.getNickname(),
                memberDataListBean.getMobile(),
                memberDataListBean.getAvatar(),
                memberDataListBean.getWeixinOpenid(),
                memberDataListBean.getSessionKey(),
                memberDataListBean.getStatus(),
                memberDataListBean.getAddTime(),
                memberDataListBean.getUpdateTime(),
                memberDataListBean.getDeleted()
        );
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public AddressData addressList(BaseParam param, String name, Integer userId) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        // 返回数据
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        // 排序
        addressExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 条件查询
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        // 未逻辑删除
        criteria.andDeletedEqualTo(false);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        List<AddressDataListBean> list = new ArrayList<>();
        for (int i = 0; i < addresses.size(); i++) {
            // 根据id查询省市区的名称
            String province = addressMapper.queryRegionNameById(Integer.parseInt(addresses.get(i).getProvince()));
            String city = addressMapper.queryRegionNameById(Integer.parseInt(addresses.get(i).getCity()));
            String country = addressMapper.queryRegionNameById(Integer.parseInt(addresses.get(i).getCounty()));
            AddressDataListBean addressDataListBean = new AddressDataListBean(
                    addresses.get(i).getId(),
                    addresses.get(i).getName(),
                    addresses.get(i).getUserId(),
                    province, city, country,
                    addresses.get(i).getAddressDetail(),
                    addresses.get(i).getAreaCode(),
                    addresses.get(i).getTel(),
                    addresses.get(i).getIsDefault(),
                    addresses.get(i).getAddTime(),
                    addresses.get(i).getUpdateTime(),
                    addresses.get(i).getDeleted()
            );
            list.add(addressDataListBean);
        }
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return new AddressData((int) total, pages, param.getLimit(), param.getPage(), list);
    }

    @Override
    public CollectData collectList(BaseParam param, Integer userId, Integer valueId) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();
        // 排序
        collectExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (valueId != null) {
            criteria.andValueIdEqualTo(valueId);
        }
        criteria.andDeletedEqualTo(false);
        List<Collect> list = collectMapper.selectByExample(collectExample);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        CollectData collectData = new CollectData(((int) total), pages, param.getLimit(), param.getPage(), list);
        return collectData;
    }

    @Override
    public FootprintData footprintList(BaseParam param, Integer userId, Integer goodsId) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        FootprintExample footprintExample = new FootprintExample();
        FootprintExample.Criteria criteria = footprintExample.createCriteria();
        // 排序
        footprintExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 条件查询
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);
        List<Footprint> list = footprintMapper.selectByExample(footprintExample);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        FootprintData footprintData = new FootprintData(((int) total), pages, param.getLimit(), param.getPage(), list);
        return footprintData;
    }

    @Override
    public SearchHistoryData searchHistoryList(BaseParam param, Integer userId, String keyword) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        // 排序
        searchHistoryExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 条件查询
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (keyword != null) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<SearchHistory> list = searchHistoryMapper.selectByExample(searchHistoryExample);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        SearchHistoryData searchHistoryData = new SearchHistoryData(((int) total), pages, param.getLimit(), param.getPage(), list);
        return searchHistoryData;
    }

    @Override
    public FeedbackData feedbackList(BaseParam param, String username, Integer id) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        FeedbackExample feedbackExample = new FeedbackExample();
        FeedbackExample.Criteria criteria = feedbackExample.createCriteria();
        // 排序
        feedbackExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 条件查询
        if (username != null) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (id != null) {
            criteria.andIdEqualTo(id);
        }
        criteria.andDeletedEqualTo(false);
        List<Feedback> list = feedbackMapper.selectByExample(feedbackExample);
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        FeedbackData feedbackData = new FeedbackData(((int) total), pages, param.getLimit(), param.getPage(), list);
        return feedbackData;
    }
}
